package vue;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import metier.DefaultHttpClientPerso;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

import com.example.finalprojet.R;

public class SuprAmis extends Activity {
	
	public int erreur=0;
	public Bitmap[] bmp;
	public Dialog dialog;
	JSONObject ok;
	public String pseudo;
	public String id;
	
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supr_amis);
        
        pseudo = getIntent().getStringExtra("pseudo");
        
        httpTasks req = new httpTasks();
        req.execute(pseudo);
        
    }

  
    
    
    
    public class httpTasks extends AsyncTask< String, Void, Object[]>   
    {


    	 protected Object[] doInBackground(String... arg0) {
    	
    		 String tabstring = null;

 	       DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
 	       
    		HttpGet httpget = new HttpGet(EcranAccueil.URLSERVEUR+"android/checkOnline.php?id="+pseudo);
    	
    			HttpResponse response = null;
    			 JSONArray main =null;
    		
    			Bitmap[] bmp = null;
    			
    			 try
    			 {
    				 response = httpclient.execute(httpget);
                     tabstring =  EntityUtils.toString(response.getEntity());
                     
                     try {
                    	 main = new JSONArray(tabstring); 
					} catch (Exception e) {
						erreur=1;
					}
                	
                	
                     
                 if ( erreur ==0)  
                 {
                	bmp = new Bitmap[main.length()];
                	
                	
                	
                	
                	for    ( int i = 0 ; i< main.length() ; i++ )
                	{
                		
                		
                		JSONObject ok = main.getJSONObject(i);
                		
                		String url = EcranAccueil.URLSERVEUR+"android/upload/smallimg";
                         url+=ok.get("id").toString()+".jpg";
                		
                	
                         
                		URLConnection conn = new URL(url).openConnection();
                		  String userpassword = "projet.echec" + ":" + "eepuhohx";
                	      String encodedAuthorization =  Base64.encodeToString( userpassword.getBytes(), Base64.NO_WRAP );
                	      conn.setRequestProperty("Authorization", "Basic "+
                	            encodedAuthorization);
                		
    	    	      	conn.connect();
    	    	      	
    	    	      	InputStream is = conn.getInputStream();
    	    	       
    	    	      	BufferedInputStream bis = new BufferedInputStream(is, 100000);
    	    	       
    	    	      	Bitmap bm = BitmapFactory.decodeStream(bis);
    	    	      	bis.close();
    	    	      	is.close();

    	    	      	bm.getScaledHeight(40);
    	    	      	bm.getScaledWidth(40);
						bmp[i] = bm;
						
						Log.d(String.valueOf(i), bmp[i].toString());
						
						
						

						
						
						
                	}  

                 }

    		} catch (Exception e)
    		{
    			Log.e("perror", e.toString());
    		}
    			
    			 try
    			 {
    			 } catch (Exception e) { e.printStackTrace();}
                	
    			 Object[] ret = new Object[2];
    			 ret[0] = tabstring;
    			 ret[1] = bmp;

    			 return ret;
    	 }

    	 
    	 
    	 
    	 
    	 
    	 
    		protected void onPostExecute(Object[] obj) 
    		{
    			
    			
    			
    			
    			bmp = (Bitmap[])obj[1];
    			String response = (String)obj[0];
    			
    			final ListView maListViewPerso;
    			HashMap<String, Object> map;
    			ArrayList<HashMap<String, Object>> listItem;
    		//	String tabstring;

    		
    		listItem = new ArrayList<HashMap<String, Object>>();
	        	maListViewPerso = (ListView)findViewById(R.id.listamis);
	        	//ImageView hihi = (ImageView)findViewById(R.id.imagee);
	    
	        	
	        	if ( erreur == 1)
	        	{
	        		Toast.makeText(getApplicationContext(),"Pas d'amis" , Toast.LENGTH_LONG).show();  
	        	}
	        	
	        	else
	        	{
  	        	

  	        try {
  	        	
  	        	

  	        	final JSONArray main = new JSONArray(response);
  	        	main.length();
  	        	
  	        	final JSONObject[] amis = new JSONObject[main.length()];
  	        	
  	        
  	        	

  	        	for    ( int i = 0 ; i< main.length() ; i++ )
  	        	{
  	        		
  	        		amis[i] = main.getJSONObject(i);
  	        		
  	        	    map = new HashMap<String, Object>();
  	        	    map.put("titre", amis[i].get("pseudo").toString());
  	                map.put("description", amis[i].get("email").toString());
  	                map.put("img", bmp[i])  ;
  	                listItem.add(map);	
  	        	} 	
	
     				
   	         SimpleAdapter mSchedule = new SimpleAdapter (getBaseContext(), listItem, R.layout.item,
                     new String[] {"img", "titre", "description"}, new int[] {R.id.img, R.id.titre, R.id.description});
   	      mSchedule.setViewBinder(new MyViewBinder());
              maListViewPerso.setAdapter(mSchedule);
  	        	
              maListViewPerso.setOnItemClickListener(new OnItemClickListener() {

      			
      			 
                
                
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					

					//String nom = main.get("amis").toString();
					String nom ="";// = main.toString();
					
					try {
						nom = amis[arg2].getString("pseudo").toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					final String name = nom;
					
					 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SuprAmis.this);
 					alertDialogBuilder.setTitle("Supprimer "+nom+"?");
 					ImageView img = new ImageView(SuprAmis.this);
     				img.setImageBitmap(bmp[arg2]);
 					
 					alertDialogBuilder.setView(img)
 						.setMessage("Etes Vous sur de supprimer "+nom+"?")
 						.setCancelable(false)
 						.setPositiveButton("Supprimer",new DialogInterface.OnClickListener() {
 							public void onClick(DialogInterface dialog,int id) {
 								SupprimerAmis SupprimerAmis = new SupprimerAmis();
 								Log.i("pseudo",pseudo);
 								Log.i("name",name);
 								String[] parametre = {name,pseudo};
 								SupprimerAmis.execute(parametre);
 								Intent nextScreen = new  Intent (getApplicationContext(), DashBoard.class );
 		        				nextScreen.putExtra("pseudo", pseudo);
 		        				startActivity (nextScreen);
 							}
 						  });
 					alertDialogBuilder
 					.setNegativeButton("Annuler",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								dialog.cancel();
							}
						  });

 						AlertDialog alertDialog = alertDialogBuilder.create();
 						alertDialog.show();

				}
                ;
      			
      			
      		
               });
			} catch (Exception e) {
				// TODO: handle exception
			}
  	        		

    		
	        	
    		
    		
	        	
    		
    		
    		
    		}
    		
    		
    		
    		
    			
    		}
    			
    			
    }
    
    
    
    
    public class MyViewBinder implements ViewBinder {

	
		
    	
    
    	
    	public boolean setViewValue(View view, Object data,String textRepresentation) {
    		if( (view instanceof ImageView) & (data instanceof Bitmap) ) {
    			ImageView iv = (ImageView) view;
    			Bitmap bm = (Bitmap) data;	
    			iv.setImageBitmap(bm);	
    			return true;
    		}
     
    		return false;
    	}
    	
    }
    
    
    
    
    
    
    
public class SupprimerAmis extends AsyncTask< String, Void, String>  {
    	
    	
    	
    	
    	protected String doInBackground(String... arg0) {
    		Log.i("supramis","ok2");
    		
    		
    		

    		DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
    	
    		HttpGet httpget = new HttpGet("http://spartacus.iutc3.unicaen.fr/~projet.echec/android/supprimeramis.php?amis="+arg0[0]+"&pseudo="+arg0[1]);
    	

    		HttpResponse response = null;
    		String responseString = null;
    		
    		
    		 try {
    		
    			 response = httpclient.execute(httpget);

    		 } catch (ClientProtocolException e) {
    		        // TODO Auto-generated catch block
    		    } catch (IOException e) {
    		        // TODO Auto-generated catch block
    		    } 
    		    
    		    HttpEntity entity = response.getEntity();
    		 
    		 if ( entity != null )
    			 try {
    				 responseString = EntityUtils.toString(entity);
    			 } catch (ParseException e) {
    					e.printStackTrace();
    			    } catch (IOException e) {
    			    	e.printStackTrace();
    			    }
    		
    		
 	      	
    		 

    		 return responseString;
    		
    			 	}

    	
    	@Override
    	protected void onPostExecute(String result) {
    		
    		
      		
				
    		
    		String amis = null;
    		
    			
    		JSONObject main = null;
    			
    			try {
    				main = new JSONObject(result);
					amis = main.get("amis").toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

    			
    			
    			
    				
    			

    			String toast = "Vous vener de supprimer : " + amis;
    				Toast.makeText(getApplicationContext(),toast , Toast.LENGTH_LONG).show();  
    				//dialog.cancel();
    				
    				
    		

    		
    			
    	}

    }
    
    
    
    
    
    
    
    
}
